package com.chinamoney.wppm.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinamoney.wppm.entity.ProcessDefinitionObj;
import com.chinamoney.wppm.entity.TaskObj;
import com.chinamoney.wppm.util.ProcessPointDefinitionUtil;


@Service
public class ActivitiService {
	
	private Logger logger = LoggerFactory.getLogger(ActivitiService.class);

	@Autowired
	private RepositoryService repositoryService;
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private IdentityService identityService;
	
	@Autowired
	private HistoryService historyService;
	
	/**
	 * 获取流程定义列表
	 * @return
	 */
	public List<ProcessDefinitionObj> getProcessDefinition() {
		// TODO Auto-generated method stub
		List<ProcessDefinition> definitions = repositoryService.createProcessDefinitionQuery().list();
		List<ProcessDefinitionObj> objDefinitions = new ArrayList<>(definitions.size());
		for(int i=0;i<definitions.size();i++) {
			ProcessDefinition processDefinition = definitions.get(i);
			objDefinitions.add(new ProcessDefinitionObj(processDefinition));
		}
		return objDefinitions;
	}
	
	/**
	 * 删除流程定义
	 */
	public void deleteProcessDefinition(String id) {
		// TODO Auto-generated method stub
		repositoryService.deleteDeployment(id, true);
	}
	
	
	/**
	 * 创建并启动流程
	 * @param definitionKey 流程定义key，系统会寻找key对应的最高版本的流程
	 */
	public void startProcessByKey(String definitionKey) {
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(definitionKey);
		identityService.setAuthenticatedUserId("Jason_Jiang");
		logger.debug(" 创建流程【"+processInstance.getName()+"】；创建人【Jason_Jiang】");
		logger.debug(" 流程详情：流程梳理所属流程定义id："+processInstance.getProcessDefinitionId()+"流程实例的id："+processInstance.getProcessInstanceId());
		HistoricProcessInstance historyProcessInstance = historyService.createHistoricProcessInstanceQuery().processDefinitionKey(definitionKey).list().get(0);
		logger.debug("流程发起人："+historyProcessInstance.getStartUserId());
	}
	
	/**
	 * 创建并启动流程
	 * @param definitionId
	 */
	public void startProcessBtId(String definitionId) {
		ProcessInstance processInstance = runtimeService.startProcessInstanceById(definitionId);
		identityService.setAuthenticatedUserId("Jason_Jiang");
		logger.debug("流程梳理所属流程定义id：" + processInstance.getProcessDefinitionId());
		logger.debug("流程实例的id：" + processInstance.getProcessInstanceId());
		logger.debug("流程实例的执行id：" + processInstance.getId());
		logger.debug("流程当前的活动（结点）id：" + processInstance.getActivityId());
		logger.debug("业务标识：" + processInstance.getBusinessKey());
		HistoricProcessInstance historyProcessInstance = historyService.createHistoricProcessInstanceQuery().processDefinitionId(definitionId).list().get(0);
		logger.debug("流程发起人："+historyProcessInstance.getStartUserId());
	}
	
	/**
	 * 获取用户当前的待处理任务
	 * @param userId
	 * @return
	 */
	public List<TaskObj> getTasksByUser(String userId) {
		List<Task> tasks = taskService.createTaskQuery().taskCandidateOrAssigned(userId).list();
		List<TaskObj> result = new ArrayList<>(tasks.size());
		for(Task task : tasks) {
			result.add(new TaskObj(task));
		}
		return result;
	}
	
	/**
	 * 根据用户名字获取任务列表
	 * @param userName
	 * @return
	 */
	public List<TaskObj> getTasksByUserName(String userName) {
		List<Task> tasks = taskService.createTaskQuery().taskAssignee(userName).list();
		List<TaskObj> result = new ArrayList<>(tasks.size());
		for(Task task : tasks) {
			result.add(new TaskObj(task));
		}
		return result;
	}
	
	/**
	 * 完成任务
	 * @param taskId：任务ID
	 * @param nextApprovers：下一个节点的审批人（id，用;隔开）
	 */
	public void complitTaskById(String taskId, String nextApprovers) {
		Map<String, Object> params = new HashMap<>();
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		String processInstanceId = task.getProcessInstanceId();
		params.put(processInstanceId+":"+ProcessPointDefinitionUtil.getNextPointName("电子需求单", task.getName()), nextApprovers);
		taskService.complete(taskId, params);
	}
	

}
